﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IEx;
using log4net;

namespace IExConsole
{
    class Program
    {
        /* To hide console window
        [DllImport("kernel32.dll")]
        static extern IntPtr GetConsoleWindow();

        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        const int SW_HIDE = 0;
        const int SW_SHOW = 5;
         */
        static DataFeed dataFeed;
        [STAThread]
        static void Main(string[] args)
        {
            GlobalContext.Properties["date"] = DateTime.Now.ToString("yyyyMMdd");
            if (args.Length == 0)
            {
                dataFeed = new DataFeed();
            }
            else
            {
                string sourceCode = string.Empty;
                Nullable<int> lang = null;
                DateTime? from = null;
                DateTime? to = null;
                bool isUpdate = false;

                /* gets value from params
                //      /u      update Pressrelease only
                //      /c      source code - required
                //      /lang   lang id - optional
                //      /from   from date in format yyyymmdd – optional
                //      /to     to date in format yyyymmdd – optional
                */
                try
                {
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (args[i].ToLower().Equals("/?"))
                        {
                            isUpdate = false;
                            sourceCode = string.Empty;
                            break;
                        }
                        switch (args[i].ToLower())
                        {
                            case "/u":
                                isUpdate = true;
                                break;
                            case "/c":
                                sourceCode = args[i + 1];
                                i++;
                                break;
                            case "/lang":
                                int langId = 0;
                                if (int.TryParse(args[i + 1], out langId))
                                {
                                    lang = langId;
                                }
                                i++;
                                break;
                            case "/from":
                                if (!string.IsNullOrEmpty(args[i + 1]))
                                {
                                    string f = args[i + 1];
                                    from = new DateTime(int.Parse(f.Substring(0, 4)), int.Parse(f.Substring(4, 2)), int.Parse(f.Substring(6, 2)));
                                    i++;
                                }
                                break;
                            case "/to":
                                if (!string.IsNullOrEmpty(args[i + 1]))
                                {
                                    string t = args[i + 1];
                                    to = new DateTime(int.Parse(t.Substring(0, 4)), int.Parse(t.Substring(4, 2)), int.Parse(t.Substring(6, 2)));
                                    i++;
                                };
                                break;
                        }
                    }
                }
                catch
                {
                    Console.WriteLine("The syntax of the command is incorrect");
                    Console.WriteLine();
                    ShowHelp();
                    return;
                }

                if (isUpdate)
                {
                    new DataFeed(true, sourceCode, lang, from, to);
                }
                else
                {
                    if (sourceCode != string.Empty)
                    {
                        if (!from.HasValue)
                            from = new DateTime(2005, 01, 01);
                        if (!to.HasValue)
                            to = DateTime.Now.Date;
                        // starts reading attachment and reupdate to database
                        dataFeed = new DataFeed(sourceCode, lang, from.Value, to.Value);
                    }
                    else
                    {
                        Console.WriteLine("The syntax of the command is incorrect");
                        Console.WriteLine();
                        ShowHelp();
                        return;
                    }
                }
            }

            if (dataFeed != null)
                GC.KeepAlive(dataFeed);
            string input = "";
            do
            {
                //Console.WriteLine("Enter \"exit\" to close program");
                input = Console.ReadLine();
            } while (!input.Equals("exit", StringComparison.OrdinalIgnoreCase));
        }

        static void ShowHelp()
        {
            string applicationName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;

            System.Text.StringBuilder cmdBuilder = new System.Text.StringBuilder();
            cmdBuilder.Append("USAGE:");
            cmdBuilder.AppendLine();
            cmdBuilder.AppendFormat("{0} /u [/? | /c companycode |", applicationName);
            cmdBuilder.AppendLine();
            cmdBuilder.AppendLine("          /from fromdate | /to todate | /lang languageid]");
            cmdBuilder.AppendLine("where");
            cmdBuilder.AppendLine("     companycode             Comany code");
            cmdBuilder.AppendLine("     fromdate                Start of date. Where the app will begin scaning from. The value must be in format: yyyymmdd");
            cmdBuilder.AppendLine("     todate                  End of date. Where the app will end to. The value must be in format: yyyymmdd");
            cmdBuilder.AppendLine("     languageid              ID of language");
            cmdBuilder.AppendLine();
            cmdBuilder.AppendLine("     Options:");
            cmdBuilder.AppendLine("         /u                      Tell the app that it should run into rescaning mode to update pressreleases only");
            cmdBuilder.AppendLine("         /c                      Tell the app that get only requests which have this company code only");
            cmdBuilder.AppendLine("         /from                   Tell the app that this is start of date to begin to scan from");
            cmdBuilder.AppendLine("         /to                     Tell the app that this is end of date to scan to");
            cmdBuilder.AppendLine("         /lang                   Tell the app that get only requests which are in this language only");
            cmdBuilder.AppendLine();
            cmdBuilder.AppendLine("The option /u must be specified to run app in update mode. If other options are not specified, default values will be used.");
            cmdBuilder.AppendLine();
            cmdBuilder.AppendLine("Examples:");
            cmdBuilder.AppendFormat("     > {0} /u /c cn-snp /from 20110101 /to 20140101 /lang 32", applicationName);

            Console.WriteLine(cmdBuilder.ToString());
        }

        static void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            if (dataFeed != null)
            {
                //dataFeed.Dispose();
            }
        }
    }
}
